import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from cls.finance.datas.top.guba import GubaSelected
from cls.finance.datas.top.tiger import TigerData
from cls.finance.system.wave5 import WaveSystem


# 实现自动登录东财帐户，获取自定义版块，监测版块内个股的量价与技术指标的变动，自动发送交易信号
class StockMonitor(object):

    def __init__(self):
        self.repeat = 0
        self.currentBlock = None
        self.loginUrl = 'https://passport2.eastmoney.com/pub/login'
        self.redirecUrl = 'http://i.eastmoney.com/stock.html'   # 需要手动进行重定向
        self.username = '18606716998'
        self.password = '221144'
        self.driver = webdriver.Chrome()
        self.driver.get(self.loginUrl)
        self.iframeLoginUrl = self.driver.find_element_by_xpath('//iframe[@id="frame_login"]').get_attribute('src')
        time.sleep(1)  # sleep一下，否则有可能报错
        self.login(self.username, self.password)
        self.guba = GubaSelected()

    # 登录东财的股票行情与设置帐户（非交易帐户）
    def login(self, username, password):
        driver = self.driver
        self.driver.get(self.iframeLoginUrl)
        time.sleep(1)
        elem_user = driver.find_element_by_xpath('//input[@id="txt_account"]')
        elem_user.click()
        elem_user.send_keys(username)
        elem_pass = driver.find_element_by_xpath('//input[@id="txt_pwd"]')
        elem_pass.send_keys(password)
        submit = driver.find_element_by_xpath('//button[@id="btn_login"]')
        submit.click()
        time.sleep(1)
        init = driver.find_element_by_xpath('//div[@class="em_init"]')
        init.click()
        self.afterInit()

    # 登录成功后手动切换页面，以及重新刷新
    def afterInit(self):
        #   登录成功后打开没有自动跳转，需要人工打开新窗口
        js = 'window.open("' + self.redirecUrl + '")'
        self.driver.execute_script(js)
        # 切换到最新打开的窗口
        self.driver.switch_to.window(self.driver.window_handles[-1])
        time.sleep(1)
        # 需要重新刷新后才能真正出现正常的页面
        self.driver.refresh()

    # 获取所有板块名称，分为两个部分，其中一部分隐藏起来了
    def getBlocks(self):
        lblocks = self.getLiblocks()
        dblocks = self.getDivblocks()
        return lblocks + dblocks

    # 分为两个部分，从Li这部分获取板块内容
    def getLiblocks(self):
        liBlocks = self.driver.find_elements_by_xpath('//ul[@id="myStockCollection"]/li')
        blocks = []
        for lblock in liBlocks:
            blocks.append(lblock.get_attribute('title'))
        return blocks

    #  从隐藏的部分获取板块内容
    def getDivblocks(self):
        divBlocks = self.driver.find_elements_by_xpath('//div[@id="moreCollectionSelect"]/span')
        blocks = []
        for dblock in divBlocks:
            blocks.append(dblock.get_attribute('title'))
        return blocks

    # 将个股添加到定义的板块中
    def add2block(self, block, code):
        self.activeBlock(block)
        inputEle = self.driver.find_element_by_xpath('//input[@id="myOwnInputCode"]')
        inputEle.clear()
        inputEle.send_keys(code)
        submit = self.driver.find_element_by_xpath('//span[@id="directAddStock"]')
        submit.click()
        time.sleep(0.1)

    #   从板块中删除个股
    def delFromBlock(self, block, code):
        self.activeBlock(block)
        item = self.driver.find_element_by_xpath('//table[@id="rightTable"]/tbody/tr/td[3]/i[@scode="' + code + '"]')
        item.click()
        confirm = self.driver.find_element_by_xpath('//div[@class="csb_btns"]//button[@class="btn btn-primary confirmyes"]')
        confirm.click()

    # 获取某个板块的所有个股
    def getBlockItems(self, bname):
        self.activeBlock(bname)
        links = self.driver.find_elements_by_xpath('//table[@id="leftTable"]//tr/td[2]/a')
        codes = []
        for link in links:
            codes.append(link.text)
        return codes

    #  清除板块的个股
    def clearBlockItems(self, bname):
        items = self.getBlockItems(bname)
        if self.repeat > 9:
            return False
        try:
            self.repeat += 1
            for code in items:
                self.delFromBlock(bname, code)
                time.sleep(0.2)
        except:
            time.sleep(2)
            self.clearBlockItems(bname)
        print('清除成功：' + bname)
        return True

    # 在页面中切换到某个板块
    def activeBlock(self, bname):
        if bname == self.currentBlock:
            return True
        lbs = self.getLiblocks()
        dbs = self.getDivblocks()
        if bname in lbs:
            li = self.driver.find_element_by_xpath('//ul[@id="myStockCollection"]/li[@title="' + bname + '"]')
            li.click()
        else:
            if bname in dbs:
                div = self.driver.find_element_by_xpath('//span[@id="topmoreCollectionSelect"]')
                ActionChains(self.driver).move_to_element(div).perform()
                # divc = self.driver.find_element_by_xpath('//div[@id="moreCollectionSelect"]')
                div.__setattr__('style', 'display: block;')
                span = self.driver.find_element_by_xpath('//div[@id="moreCollectionSelect"]/span[@title="' + bname + '"]')
                span.click()
                div.__setattr__('style', 'display: none;')
            else:
                print('没有匹配的板块')
        self.currentBlock = bname
        time.sleep(1)
        return True

    def getHotestItems(self):
        pass

    def addguba2block(self, block):
        items = self.guba.items
        for item in items:
            self.add2block(block, item)
        print('成功添股吧个股到“热门”板块')

    def addTiger2Block(self, block):
        obj = TigerData()
        df = obj.getStatisticLists()
        listCode = df[['code']].T.values[0]  # 对dataframe进行转置后，提取第一行
        self.addResBblock(block, listCode)
        return True

    def addResBblock(self, block, codesArr):
        for code in codesArr:
            self.add2block(block, code)
            print('添加' + code + '到=' + block + '=板块成功')
        return True


#

obj = StockMonitor()
wave = WaveSystem()
res = wave.getList()
# # obj.guba.save2sql()
# obj.clearBlockItems('tigers')
# # obj.addTiger2Block('tigers')
obj.addResBblock('tigers', res)
